import { Injectable } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { ArticleContentShareEntity } from './article-content-share.entity';
import { DataSource, Repository } from 'typeorm';
import { UserEntity } from '~/modules/user/user.entity';
import { UserWechatEntity } from '~/modules/user/user-wechat/user-wechat.entity';
import { ArticleContentEntity } from '../article-content.entity';

@Injectable()
export class ArticleContentShareService {
  constructor(
    @InjectRepository(ArticleContentShareEntity)
    private readonly articleContentShareRepo: Repository<ArticleContentShareEntity>,
    @InjectDataSource()
    private readonly datasource: DataSource
  ) {}

  /**
   * 创建文章分享记录
   * @param contentId 文章内容ID
   * @param userId 用户ID
   * @returns 创建的分享记录
   */
  async create(contentId: number, userId: number): Promise<ArticleContentShareEntity> {
    return await this.articleContentShareRepo.save({
      user: { id: userId },
      content: { id: contentId },
    });
  }

  /**
   * 统计数据
   * @returns
   */
  async getAllCount(): Promise<Partial<ArticleContentShareEntity>[]> {
    return await this.datasource
      .createQueryBuilder()
      .addSelect('article_share.created_at', 'createdAt')
      .addSelect('userWechat.nickname', 'nickname')
      .addSelect('userWechat.phone', 'phone')
      .addSelect('articleContent.code', 'articleCode')
      .addSelect('articleContent.name', 'articleName')
      .from(ArticleContentShareEntity, 'article_share')
      .leftJoin(UserEntity, 'user', 'user.id = article_share.user_id')
      .leftJoin(UserWechatEntity, 'userWechat', 'userWechat.id = user.wechat_id')
      .leftJoin(
        ArticleContentEntity,
        'articleContent',
        'articleContent.id = article_share.content_id'
      )
      .orderBy('article_share.id', 'DESC')
      .getRawMany();
  }
}
